//
//  WebViewController.swift
//  Swift-WB
//
//  Created by lxy on 2017/6/8.
//  Copyright © 2017年 lixiya. All rights reserved.
//

import UIKit
import WebKit


enum WebLoadType {
    case url
    case html
}

class WebViewController: UIViewController {
    var urlString: String?
    var htmlString: String?
    var loadType: WebLoadType = .url // 默认url
    
    

    lazy var webView: WebView = {
        let webView = WebView(frame: self.view.bounds, scriptMessageHandlerNames: ["test"])
        webView.wb_delegate = self
        webView.navigationDelegate = self
        webView.uiDelegate = self
        return webView
    }()
   
    lazy var progressView: UIProgressView = {
        let progressView = UIProgressView(progressViewStyle: .default)
        progressView.frame = CGRect(x: 0, y: 64, width: self.view.frame.width, height: 20)
        progressView.tintColor = UIColor.red
        progressView.trackTintColor = UIColor.white
        return progressView
    }()
    
    lazy var closeBtItem: UIBarButtonItem = {
        let closeBtItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeBtItemAction))
        return closeBtItem
    }()
    
    lazy var backBtItem: UIBarButtonItem = {
        let backBtItem = UIBarButtonItem(image: UIImage(named:"nav_back_nor"), style: .plain, target: self, action: #selector(backBtItemAction))
        return backBtItem
    }()

    /*
     *初始化方式1
     *重写构造函数，这种方式初始化改类的时候只能用 WebViewController(urlString: "https://www.baidu.com") 这个方法了，原来的 WebViewController() 会被覆盖 只有在类里面声明了的才可以用作初始化函数
     */
    /*
    init(urlString: String) {
        self.urlString = urlString
        super.init(nibName: nil, bundle: nil)
    }
    
     /* required 作用？？？？*/
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    */
    
    
    /*
     *初始化方式2
     *遍历构造函数
     */
    convenience init(urlString: String) {
        self.init(nibName: nil, bundle: nil)
        self.urlString = urlString
        self.loadType = .url
    }
    
    convenience init(htmlString: String) {
        self.init(nibName: nil, bundle: nil)
        self.htmlString = htmlString
        self.loadType = .html
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        //self.navigationItem.leftBarButtonItems = [backBtItem,closeBtItem]
        
        self.view.addSubview(webView)
        self.view.addSubview(progressView)
        
        switch loadType {
        case .url:
            webView.load(URLRequest(url: URL(string: urlString!)!))
        case .html:
            webView.loadHTMLString(htmlString!, baseURL: nil)
        }
    }
    
    
    //MARK: - Events
    func closeBtItemAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
    func backBtItemAction() {
        if webView.canGoBack {
            webView.goBack()
        }else {
            self.navigationController?.popViewController(animated: true)
        }
    }

}

// MARK: - WebViewDelegate
extension WebViewController: WebViewDelegate {

    func wb_title(_ title: String?) {
        print("---\(String(describing: title))---")
        self.navigationItem.title = title
    }
    
    func wb_estimatedProgress(_ progress: Float) {
        print("---\(progress)---")
        if progress == 1 {
            self.progressView.setProgress(1.0, animated: true)
            UIView.animate(withDuration: 0.5, animations: {
                self.progressView.alpha = 0.0
            }, completion: { (completion) in
                self.progressView.setProgress(0.0, animated: false)
            })
        }else {
            self.progressView.alpha = 1.0
            self.progressView.setProgress(progress, animated: true)

        }
    
    }
    
    func wb_receiveScriptMessage(_ message: WKScriptMessage) {
        
    }
    
}

// MARK: - WKUIDelegate
extension WebViewController: WKUIDelegate {
    
    // 弹出框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) -> Void in
            completionHandler()
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) -> Void in
            completionHandler()
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    // 弹出框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        
        let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) -> Void in
            completionHandler(true)
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) -> Void in
            completionHandler(false)
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    // 文本输入弹出框
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        
        let alert = UIAlertController(title: prompt, message: defaultText, preferredStyle: .alert)
        alert.addTextField { (textField: UITextField) -> Void in
            textField.textColor = UIColor.red
        }
        alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) -> Void in
            completionHandler(alert.textFields![0].text!)
        }))
        self.present(alert, animated: true, completion: nil)
    }

}


// MARK: - WKNavigationDelegate
extension WebViewController: WKNavigationDelegate {
    //在发送请求之前，决定是否继续处理。根据webView、navigationAction相关信息决定这次跳转 是否可以继续进行,这些信息包含HTTP发送请求，如头部包含User-Agent,Accept。
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        let url = navigationAction.request.url?.absoluteString
        print("url---\(String(describing: url))----")
        
        if url?.hasPrefix("https://www.baidu.com/?code=") == true{
            
            if  let rang = url?.range(of: "code="),
                let code = url?.substring(from: rang.upperBound) {
                print("code---\(code)----")
                
                WBUserDataHelper.shared.wbOAuth(code, success: { (response) in
                    
                }, failure: { (error) in
                    
                })
                
            }
        }
        // 这里根据业务决定是否
        decisionHandler(.allow)
    }
    
    //开始加载页面调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print(#function)
    }
    
    //在收到响应后，决定是否继续处理。根据response相关信息，可以决定这次跳转是否可以继续进行。
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        print(#function)
        decisionHandler(.allow)
    }
    
    //页面加载完成后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print(#function)
    }
    
    //页面加载失败时候调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print(#function)
    }
}
